# 百度翻译网络蜘蛛主函数
import requests
import json
class BaiduTranslateSpider:
    def __init__(self):
        self.domain = "https://fanyi.baidu.com"
        self.headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Origin': 'https://fanyi.baidu.com',
            'Pragma': 'no-cache',
            'Referer': 'https://fanyi.baidu.com/mtpe-individual/multimodal',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
            'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        self.cookies = {
            'BAIDUID': '3F703C99C9DB8305DCD3025BCB6D17F7:FG=1', # 需要更改成你自己的
            'BAIDUID_BFESS': '3F703C99C9DB8305DCD3025BCB6D17F7:FG=1', # 需要更改成你自己的
            # 'ab_sr': '1.0.1_NTU0OWYxYjI4Yjc3ZDQ2OGIxZjQwODliNTBjNWNhNzVmYmI4YzM2N2VlNmUxYzc1MGI3MWJkNjQxNWJhNjg3MDdiM2FiYWVjNGE1NWVhZmU4NDk0ZTIyNDk5YWU3MjI3NTVmYWE4YTY0NzhmY2VhYzc1MmIwM2E3NGZkYzM5YmFhNTRhYTM3YzYxY2E1OGMxZjI5Y2VkOTU2OTU2Y2ZlYw==',
            # 'RT': '"z=1&dm=baidu.com&si=fbd5ef5d-8539-4919-9752-f00b8772b62c&ss=m7keh38p&sl=2&tt=3f5&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=f6v"',
        }
    # 识别语言
    def identify_language(self, text):
        data = {
            'query': text,
        }

        response = requests.post(f'{self.domain}/langdetect', headers=self.headers, data=data, cookies=self.cookies).json()
        return response

    # 翻译
    def translate(self, text, from_lang, to_lang):
        # 翻译结果
        result = [] 
        json_data = {
            'query': text,
            'from': from_lang,
            'to': to_lang,
            'reference': '',
            'corpusIds': [],
            'needPhonetic': True,
            'domain': 'common',
        }

        response = requests.post(f'{self.domain}/ait/text/translate',stream=True, cookies=self.cookies, headers=self.headers, json=json_data)
        for line in response.iter_lines():
            if line:
                line = line.decode('utf-8')
                if "event: message" in line:
                    continue
                line = line.replace('data: ', '')
                line = json.loads(line)
                if line['errno'] == 10001:
                    result.append([{"dst": f"翻译失败 {line['errmsg']}"}])
                    break
                line = line['data']
                
                if line['message'] == "翻译中":
                    line = line['list']
                    result.append(line)
                else:
                    continue
        if len(result) > 0:
            return result[0]
        else:
            return []

    # 获取翻译建议
    def sug(self, text):
        data = {
            'kw': text,
        }
        response = requests.post(f'{self.domain}/sug', headers=self.headers, data=data, cookies=self.cookies).json()
        return response

if __name__ == '__main__':
    spider = BaiduTranslateSpider()
    print(spider.sug('你好'))

